import cherrypy
from django.utils import simplejson

from app.controllers.role import RoleController
from app.dutil import toClass

class RoleHandler(object):
	@cherrypy.expose
	def index(self):
		pass
  
	@cherrypy.expose	
	def roles(self, *args, **kwarg):
		rsRoles = RoleController.getRoles()
		dRoles = dict([('page',1), ('rows',[rRole.toCells() for rRole in rsRoles])])
		dRoles.update(total=len(dRoles['rows']))
		return simplejson.dumps(dRoles)
		
	@cherrypy.expose
	def vrole(self,id=None):
		try:
			rsRole = RoleController.getRole(int(id))
			dRole = rsRole.toRow()
			return simplejson.dumps(dRole)
		except TypeError:
			return None
			
	@cherrypy.expose
	def urole(self, *args, **kwargs):
		if kwargs:
			brs = RoleController.updateRole(toClass(kwargs))
		else: brs = False
			
		return simplejson.dumps(dict([('success',brs)]))
	
	@cherrypy.expose
	def arole(self, *args, **kwargs):
		if kwargs:
			brs = RoleController.addRole(toClass(kwargs))
		else: brs = False
			
		return simplejson.dumps(dict([('success',brs)]))
	
	@cherrypy.expose
	def drole(self, id=None):
		if id is not None:
			brs = RoleController.deleteRole(id)
		else: brs = False
		
		return simplejson.dumps(dict([('success',brs)]))


